import * as path from "path";
import * as fs from "fs";
import * as os from "os";
import * as fse from 'fs-extra';
import * as vscode from "vscode";
import localize from "../localize";
import { WebviewPanel } from "vscode";
//import { gContext, createProject } from "../extension";
import * as utils from "../utils";
import { ViewManager } from "../common/viewManager";
import { BaseManager } from "../BaseManager";

export class OperationPage extends BaseManager {
    kyProjectIdePath: string;
    context: vscode.ExtensionContext;
    constructor(context: vscode.ExtensionContext) {
        super(context);
        this.context = context;
        this.kyProjectIdePath = "";
    }

    getProjectJson = () => {
        
        if (vscode.workspace.rootPath) {
            this.kyProjectIdePath =
                vscode.workspace.rootPath + "/" + "vsproject.ide.json";
            // vscode.window.showInformationMessage(vscode.workspace.rootPath);
            if (
                !(
                    fs.existsSync(this.kyProjectIdePath) &&
                    fs.statSync(this.kyProjectIdePath).isFile()
                )
            ) {
                vscode.window.showInformationMessage(
                    localize("extension.project.noprojectidefile")
                );
            } else {
                return JSON.parse(
                    fs.readFileSync(this.kyProjectIdePath, "utf8")
                );
            }
        }
        return [];
    }

    /**
    * 定义项目创建时接收信息处理函数
    * @param viewPanel 页面
    * @param message 信息
    * @returns 
    */
    onListener = async (
        view: vscode.WebviewView,
        message: any
    ) => {
        //test
        console.log("OperationPage message " + message.type);

        if (vscode.workspace.workspaceFolders == undefined) {
            console.log("no project");
            return;
        }

        var workspacePath = vscode.workspace.rootPath;
        var tasksJsonData: vscode.WorkspaceConfiguration;
        var launchJsonData: vscode.WorkspaceConfiguration;

        let vsprojectidejson = this.getProjectJson();
        const languagedata = vsprojectidejson["language"];
        const templatedata = vsprojectidejson["template"];
        const buildTools = vsprojectidejson["buildTools"];

        //获取tasks.json中的task任务信息
        tasksJsonData = vscode.workspace.getConfiguration("tasks");
        //获取launch.json中launch中的configurations信息
        launchJsonData = vscode.workspace.getConfiguration("launch");
        let tasksValue = tasksJsonData.get<any[]>("tasks");
        let launchValue = launchJsonData.get<any[]>("configurations");

        //检测taskValue是否获取到数值
        if (tasksValue == undefined) {
            console.log("Error:read tasks.json");
            return;
        }
        //检测launchValue是否获取到数值
        if (launchValue == undefined) {
            console.log("Error:read launch.json");
            return;
        }

        //检查共享库是否都已安装
        utils.getSystemPlatform();
        // 翻页检查
        if (message.type === 'OPERATION') {
            var msg = '';
            console.log("message.page: " + message.page);
            console.log("message.dataPages: ")
            console.log(message.dataPages);

            msg = await this.checkDataConf(message, false);

            var err = 'false';
            if (msg != '') {
                err = 'true'
            }
            // 发送消息
            view.webview.postMessage({
                type: 'CHECK_DATA',
                way: message.way,
                error: err,
                message: msg
            });
            // vscode.window.showErrorMessage(msg);
            return;
        }
    };
    
    checkDataConf = async (message: any, isCheckAll: boolean = false) => {
        let msg = "";
        try{
            if(message.data === undefined || (!isCheckAll && message.dataPages === undefined)){
                // 数据不完整 报错
                msg = localize("language.errorData");
            }
            if (msg == '' && (isCheckAll || message.page >= message.dataPages.projectPath)) {
                // 判断项目目录
                if (msg == '') {
                    let isOk = await utils.isPathLegalSync(message.data.projectPath);
                    if(!isOk){
                        msg = localize("language.errorProjectPath");
                    }
                }
            }
        }catch(e){
            console.log(e)
            msg = localize("language.errorData");
        }
        return msg;
    }
    /**
     * 注册创建默认模版命令
     * @returns 
     */
    registerOperationPages(context : vscode.ExtensionContext) {
        // 注册命令
        let viewId = 'project.operationView';
        let provider = ViewManager.createWebviewViewProvider(
            {
            // html 文件名
            path: "operationProjectPage",
            // 页面标题
            title: localize("language.operation-project"),
            splitView: false,
            extensionUri: context.extensionUri,
            // 监听
            listener: this.onListener,
        });

        context.subscriptions.push(
            vscode.window.registerWebviewViewProvider('project.operationView', provider)
        );
        context.subscriptions.push(
            vscode.commands.registerCommand('project.operationTwo', () => {
                // provider.status(0);
            }));
        context.subscriptions.push(
            vscode.commands.registerCommand('project.operationOne', () => {
            // provider.clearColors();
        }));
        // ViewManager.createWebviewViewProviderAsync(
        //     {
        //     // html 文件名
        //     path: "operationProjectPage",
        //     // 页面标题
        //     title: localize("language.operation-project"),
        //     splitView: false,
        //     extensionUri: context.extensionUri,
        //     // 监听
        //     listener: this.onListener,
        // }).then(provider => {
        //     context.subscriptions.push(
        //         vscode.window.registerWebviewViewProvider('project.operationView', provider)
        //     );
        //     context.subscriptions.push(
        //         vscode.commands.registerCommand('project.operationTwo', () => {
        //             provider.status(0);
        //         }));
        //         context.subscriptions.push(
        //             vscode.commands.registerCommand('project.operationOne', () => {
        //             provider.clearColors();
        //         }));
                
        // });
//   const provider = new SidebarViewProvider(context.extensionUri);

//   context.subscriptions.push(
//       vscode.window.registerWebviewViewProvider(SidebarViewProvider.viewType, provider));

//   context.subscriptions.push(
//       vscode.commands.registerCommand('project.operationTwo', () => {
//           provider.buildProject();
//       }));

//   context.subscriptions.push(
//       vscode.commands.registerCommand('project.operationOne', () => {
//           provider.clearColors();
//       }));
    }

}
